import oss2
import uuid
import os
from config import config
from models.user import UserModel

class AvatarService:
    """头像服务类 - 处理用户头像上传到阿里云OSS"""
    
    def __init__(self):
        # 从环境变量获取OSS配置信息
        self.access_key_id = os.getenv('OSS_ACCESS_KEY_ID')
        self.access_key_secret = os.getenv('OSS_ACCESS_KEY_SECRET')
        self.bucket_name = 'yming-car-bigdata'
        self.endpoint = 'oss-cn-beijing.aliyuncs.com'
        self.auth = None
        self.bucket = None
        
        # 初始化OSS客户端
        if self.access_key_id and self.access_key_secret:
            self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
            self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)
        
        self.user_model = UserModel()
    
    def upload_avatar(self, username, file_data, file_extension):
        """
        上传用户头像到阿里云OSS
        
        Args:
            username (str): 用户名
            file_data (bytes): 文件二进制数据
            file_extension (str): 文件扩展名（如.jpg, .png等）
            
        Returns:
            dict: 包含上传结果的字典
        """
        try:
            # 检查OSS配置
            if not self.bucket:
                return {
                    'success': False,
                    'message': 'OSS配置不完整，请检查环境变量设置'
                }
            
            # 生成随机文件名
            filename = f"{uuid.uuid4().hex}{file_extension}"
            object_key = f"avatar/{filename}"
            
            # 上传文件到OSS
            self.bucket.put_object(object_key, file_data)
            
            # 构建文件访问URL
            avatar_url = f"https://{self.bucket_name}.{self.endpoint}/{object_key}"
            
            # 更新用户数据库中的头像URL
            result = self.user_model.update_user(username, {'avatar': avatar_url})
            
            if result['success']:
                return {
                    'success': True,
                    'message': '头像上传成功',
                    'avatar_url': avatar_url
                }
            else:
                return {
                    'success': False,
                    'message': f'数据库更新失败: {result["message"]}'
                }
                
        except oss2.exceptions.OssError as e:
            print(f"OSS上传错误: {e}")
            return {
                'success': False,
                'message': f'OSS上传失败: {str(e)}'
            }
        except Exception as e:
            print(f"头像上传异常: {e}")
            return {
                'success': False,
                'message': f'头像上传异常: {str(e)}'
            }
    
    def delete_avatar(self, username):
        """
        删除用户头像（从OSS和数据库中）
        
        Args:
            username (str): 用户名
            
        Returns:
            dict: 包含删除结果的字典
        """
        try:
            # 获取用户当前头像URL
            user = self.user_model.get_user_by_username(username)
            if not user or not user.get('avatar'):
                return {
                    'success': False,
                    'message': '用户没有设置头像'
                }
            
            avatar_url = user['avatar']
            
            # 从URL中提取OSS对象key
            # URL格式: https://bucket.endpoint/object_key
            object_key = avatar_url.split(f"{self.bucket_name}.{self.endpoint}/")[-1]
            
            # 从OSS删除文件（仅在bucket存在时执行）
            if self.bucket:
                self.bucket.delete_object(object_key)
            
            # 更新数据库，清空avatar字段
            result = self.user_model.update_user(username, {'avatar': None})
            
            if result['success']:
                return {
                    'success': True,
                    'message': '头像删除成功'
                }
            else:
                return {
                    'success': False,
                    'message': f'数据库更新失败: {result["message"]}'
                }
                
        except oss2.exceptions.OssError as e:
            print(f"OSS删除错误: {e}")
            return {
                'success': False,
                'message': f'OSS删除失败: {str(e)}'
            }
        except Exception as e:
            print(f"头像删除异常: {e}")
            return {
                'success': False,
                'message': f'头像删除异常: {str(e)}'
            }